import SockJS from 'sockjs-client'
import Stomp from 'stompjs'

class WebSocketService {
  constructor() {
    this.stompClient = null
    this.connected = false
  }

  connect(token, onMessageReceived) {
    const socket = new SockJS('http://localhost:8080/api/ws')
    this.stompClient = Stomp.over(socket)
    
    this.stompClient.connect(
      { Authorization: `Bearer ${token}` },
      (frame) => {
        console.log('Connected: ' + frame)
        this.connected = true
        
        // 订阅个人消息队列
        this.stompClient.subscribe('/user/queue/messages', (message) => {
          if (onMessageReceived) {
            onMessageReceived(JSON.parse(message.body))
          }
        })
      },
      (error) => {
        console.error('WebSocket connection error:', error)
        this.connected = false
      }
    )
  }

  sendMessage(message) {
    if (this.stompClient && this.connected) {
      this.stompClient.send('/app/chat/send', {}, JSON.stringify(message))
    }
  }

  disconnect() {
    if (this.stompClient) {
      this.stompClient.disconnect()
      this.connected = false
    }
  }
}

export default new WebSocketService()

